<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/@tailwindcss/browser@4.1.6/dist/index.global.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <title>编程概念演示</title>
    <style>
        .grid-cell {
            width: 20px;
            height: 20px;
            border: 1px solid #ccc;
            box-sizing: border-box;
        }

        .filled {
            background-color: #000;
        }

        #board {
            display: flex;
            flex-wrap: wrap;
            width: calc(16 * 20px);
        }

        .current-cell {
            border: 2px solid red;
        }

        .command-display {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin: 10px;
        }

        .command-arrow {
            width: 20px;
            height: 20px;
            background-color: #eee;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 3px;
        }

        .command-arrow.current {
            border: 2px solid red;
        }
    </style>
</head>

<body class="bg-gray-100 flex flex-col items-center justify-center">
    <div id="board" class="flex flex-wrap mb-4"></div>
    <div class="command-display" id="command-display"></div>
    <div class="flex gap-2 mt-2">
        <button id="execute-button" class="bg-blue-500 text-white p-2 rounded-md hover:bg-blue-600">执行</button>
        <button id="clear-button" class="bg-red-500 text-white p-2 rounded-md hover:bg-red-600">清除指令</button>
        <button id="clear-board-button" class="bg-yellow-500 text-white p-2 rounded-md hover:bg-yellow-600">清除画板</button>

        <!-- 新增执行速度下拉框 -->
        <div class="ml-2">
            <label for="speed-select" class="text-sm text-gray-600 mr-1">执行速度:</label>
            <select id="speed-select" class="p-1 border rounded">
                <option value="500">500ms</option>
                <option value="100">100ms</option>
                <option value="50">50ms</option>
            </select>
        </div>
        <!-- 新增演示模式开关 -->
        <div class="ml-2">
            <label for="demo-mode-checkbox" class="text-sm text-gray-600 mr-1">演示模式:</label>
            <input type="checkbox" id="demo-mode-checkbox">
        </div>
    </div>
    <div class="mt-4 text-sm text-gray-600">
        <p>使用方向键 (↑↓←→) 移动，空格键填充</p>
    </div>
    <div class="mt-2 flex gap-2">
        <button id="square-example-button" class="bg-purple-500 text-white p-2 rounded-md hover:bg-purple-600">画方框示例</button>
        <button id="example-button" class="bg-green-500 text-white p-2 rounded-md hover:bg-green-600">写出刘字示例</button>
    </div>

    <!-- 新增指令粘贴功能 -->
    <div class="mt-4 flex gap-2 items-center">
        <input type="text" id="commands-input" placeholder="在此粘贴指令序列" class="p-2 border rounded-md w-[600px]">
        <button id="paste-button" class="bg-blue-500 text-white p-2 rounded-md hover:bg-blue-600">导入指令</button>
    </div>

    <script>
        const board = document.getElementById('board');
        const commandDisplay = document.getElementById('command-display');
        const executeButton = document.getElementById('execute-button');
        const exampleButton = document.getElementById('example-button');
        const clearButton = document.getElementById('clear-button');
        const clearBoardButton = document.getElementById('clear-board-button');
        const squareExampleButton = document.getElementById('square-example-button');
        // 获取速度选择下拉框
        const speedSelect = document.getElementById('speed-select');
        // 获取演示模式开关
        const demoModeCheckbox = document.getElementById('demo-mode-checkbox');

        const gridSize = 16;
        let currentX = 0;
        let currentY = 0;
        let commands = [];
        let isExecuting = false;
        let currentCommandIndex = 0;
        // 默认执行速度
        let executionSpeed = 500;
        // 演示模式开关
        let isDemoMode = false;

        // 创建画板
        for (let y = 0; y < gridSize; y++) {
            const row = document.createDocumentFragment();
            for (let x = 0; x < gridSize; x++) {
                const cell = document.createElement('div');
                cell.classList.add('grid-cell');
                row.appendChild(cell);
            }
            board.appendChild(row);
            console.log(`第 ${y + 1} 行格子已输出`);
        }

        // 获取当前格子元素
        function getCurrentCell() {
            return board.children[currentY * gridSize + currentX];
        }

        // 移除之前的当前格子标记
        function removeCurrentCellMarker() {
            const prevCell = board.querySelector('.current-cell');
            if (prevCell) {
                prevCell.classList.remove('current-cell');
            }
        }

        // 标记当前格子
        function markCurrentCell() {
            const currentCell = getCurrentCell();
            currentCell.classList.add('current-cell');
        }

        // 移除之前的当前指令标记
        function removeCurrentCommandMarker() {
            const prevCommand = commandDisplay.querySelector('.command-arrow.current');
            if (prevCommand) {
                prevCommand.classList.remove('current');
            }
        }

        // 标记当前指令
        function markCurrentCommand(index) {
            removeCurrentCommandMarker();
            if (index < commandDisplay.children.length) {
                commandDisplay.children[index].classList.add('current');
            }
        }

        // 添加指令到显示区域
        function addCommandToDisplay(command) {
            const commandElement = document.createElement('div');
            commandElement.classList.add('command-arrow');

            switch (command) {
                case 'u':
                    commandElement.innerHTML = '<i class="fa-solid fa-arrow-up"></i>';
                    break;
                case 'd':
                    commandElement.innerHTML = '<i class="fa-solid fa-arrow-down"></i>';
                    break;
                case 'l':
                    commandElement.innerHTML = '<i class="fa-solid fa-arrow-left"></i>';
                    break;
                case 'r':
                    commandElement.innerHTML = '<i class="fa-solid fa-arrow-right"></i>';
                    break;
                case 'f':
                    commandElement.innerHTML = '<i class="fa-solid fa-square"></i>';
                    break;
            }

            commandDisplay.appendChild(commandElement);
        }

        // 执行指令
        function executeCommand(command) {
            removeCurrentCellMarker();
            switch (command) {
                case 'u':
                    if (currentY > 0) currentY--;
                    break;
                case 'd':
                    if (currentY < gridSize - 1) currentY++;
                    break;
                case 'l':
                    if (currentX > 0) currentX--;
                    break;
                case 'r':
                    if (currentX < gridSize - 1) currentX++;
                    break;
                case 'f':
                    getCurrentCell().classList.add('filled');
                    break;
            }
            markCurrentCell();
        }

        // 按用户选择的速度执行指令
        function executeCommandsSequentially(commands) {
            if (isExecuting) return;
            isExecuting = true;
            currentCommandIndex = 0;

            function executeNext() {
                if (currentCommandIndex < commands.length) {
                    removeCurrentCommandMarker();
                    const command = commands[currentCommandIndex];
                    if (command) {
                        executeCommand(command);
                        markCurrentCommand(currentCommandIndex);
                    }
                    currentCommandIndex++;
                    setTimeout(executeNext, executionSpeed);
                } else {
                    isExecuting = false;
                    removeCurrentCommandMarker();
                }
            }

            executeNext();
        }

        // 模拟字库
        const fontLibrary = {
            '刘': [
                [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
                [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
                [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
                [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0],
                [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0],
                [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0],
                [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0],
                [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],
                [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],
                [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],
                [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],
                [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],
                [0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
                [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0],
                [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
            ]
        };

        // 根据字库生成指令
        function generateCommandsFromFont(fontMatrix) {
            let commands = '';
            let moveDir = 1; // left or right
            for (let y = 0; y < gridSize; y++) {
                let xInit = 0;
                if (moveDir < 0) {
                    xInit = gridSize;
                }
                for (let x = xInit; (moveDir > 0 && x < gridSize) || (moveDir < 0 && x >= 0); x += moveDir) {
                    if (x > 0 && moveDir > 0) {
                        commands += 'r';
                    } else if (x < gridSize - 1 && moveDir < 0) {
                        commands += 'l';
                    }
                    if (fontMatrix[y][x] === 1) {
                        commands += 'f';
                    }
                }
                if (y < gridSize - 1) {
                    commands += 'd';
                    moveDir *= -1;
                }
            }
            return commands;
        }

        // 生成刘字指令
        const liuCommands = generateCommandsFromFont(fontLibrary['刘']);

        // 生成6×6方框指令
        function generateSquareCommands() {
            let commands = '';
            const size = 6; // 方框大小

            // 画上边
            for (let i = 0; i < size; i++) {
                commands += 'r';
                commands += 'f';
            }
            // 画右边
            for (let i = 0; i < size; i++) {
                commands += 'd';
                commands += 'f';
            }
            // 画下边
            for (let i = 0; i < size; i++) {
                commands += 'l';
                commands += 'f';
            }
            // 画左边
            for (let i = 0; i < size; i++) {
                commands += 'u';
                commands += 'f';
            }

            return commands;
        }

        const squareCommands = generateSquareCommands();

        // 清除画板
        function clearBoard() {
            if (isExecuting) return;

            const cells = board.querySelectorAll('.grid-cell');
            cells.forEach(cell => {
                cell.classList.remove('filled');
            });
            
            // 重置当前位置到左上角
            removeCurrentCellMarker();
            currentX = 0;
            currentY = 0;
            markCurrentCell();
        }

        // 更新执行速度（修复后的代码）
        function updateExecutionSpeed() {
            executionSpeed = parseInt(speedSelect.value);
            console.log(`执行速度已更新为: ${executionSpeed}ms`);
        }

        // 切换演示模式
        function toggleDemoMode() {
            isDemoMode = demoModeCheckbox.checked;
        }

        // 绑定键盘事件
        document.addEventListener('keydown', (event) => {
            if (isExecuting) return;

            let command = '';

            switch (event.key) {
                case 'ArrowUp':
                    command = 'u';
                    break;
                case 'ArrowDown':
                    command = 'd';
                    break;
                case 'ArrowLeft':
                    command = 'l';
                    break;
                case 'ArrowRight':
                    command = 'r';
                    break;
                case ' ':
                    command = 'f';
                    event.preventDefault(); // 防止空格滚动页面
                    break;
                default:
                    return; // 忽略其他按键
            }

            commands.push(command);
            addCommandToDisplay(command);

            // 如果处于演示模式，立即执行指令
            if (isDemoMode) {
                executeCommand(command);
            }
        });

        // 绑定示例按钮点击事件
        exampleButton.addEventListener('click', () => {
            if (isExecuting) return;

            // 清空当前指令
            commands = [];
            commandDisplay.innerHTML = '';

            // 添加刘字指令
            for (const command of liuCommands) {
                commands.push(command);
                addCommandToDisplay(command);
            }

            // 执行刘字指令
            executeCommandsSequentially(commands);
        });

        // 绑定画方框示例按钮点击事件
        squareExampleButton.addEventListener('click', () => {
            if (isExecuting) return;

            // 清空当前指令
            commands = [];
            commandDisplay.innerHTML = '';

            // 添加画方框指令
            for (const command of squareCommands) {
                commands.push(command);
                addCommandToDisplay(command);
            }

            // 执行画方框指令
            executeCommandsSequentially(commands);
        });

        // 绑定执行按钮点击事件
        executeButton.addEventListener('click', () => {
            if (isExecuting) return;
            // 显示当前指令到输入框
            commandsInput.value = commands.join('');
            executeCommandsSequentially(commands);
        });

        // 绑定清除按钮点击事件
        clearButton.addEventListener('click', () => {
            if (isExecuting) return;

            // 在清除前输出当前指令到控制台
            console.log('即将清除的指令序列:', commands.join(''));
            commandsInput.value = commands.join('');
            console.log('指令含义: u=上, d=下, l=左, r=右, f=填充');

            // 清空指令
            commands = [];
            commandDisplay.innerHTML = '';

            // 重置当前位置
            removeCurrentCellMarker();
            currentX = 0;
            currentY = 0;
            markCurrentCell();
        });

        // 绑定清除画板按钮点击事件
        clearBoardButton.addEventListener('click', clearBoard);

        // 绑定速度选择下拉框事件（修复后的代码）
        speedSelect.addEventListener('change', updateExecutionSpeed);

        // 绑定演示模式开关事件
        demoModeCheckbox.addEventListener('change', toggleDemoMode);

        // 验证指令是否合法
        function isValidCommand(command) {
            return ['u', 'd', 'l', 'r', 'f'].includes(command);
        }

        // 新增指令粘贴功能
        const commandsInput = document.getElementById('commands-input');
        const pasteButton = document.getElementById('paste-button');

        pasteButton.addEventListener('click', () => {
            if (isExecuting) return;

            const inputCommands = commandsInput.value.toLowerCase().split('');
            const validCommands = inputCommands.filter(cmd => isValidCommand(cmd));

            if (validCommands.length === 0) {
                alert('没有找到有效的指令！\n有效指令：u=上, d=下, l=左, r=右, f=填充');
                return;
            }

            if (validCommands.length !== inputCommands.length) {
                alert('部分指令无效，仅导入有效指令。\n有效指令：u=上, d=下, l=左, r=右, f=填充');
            }

            // 清空现有指令
            commands = [];
            commandDisplay.innerHTML = '';

            // 添加新指令
            validCommands.forEach(command => {
                commands.push(command);
                addCommandToDisplay(command);
            });

            // 清空输入框
            commandsInput.value = '';

            // 重置当前位置
            removeCurrentCellMarker();
            currentX = 0;
            currentY = 0;
            markCurrentCell();
        });

        // 初始化当前格子标记
        markCurrentCell();
        
        // 初始化执行速度
        updateExecutionSpeed();
    </script>
</body>

</html>